package com.da.boot.autowire;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author JokerDa.
 * @date 2021/8/31 11:03
 * Description:众所周知，springmvc的启动是在DisptachServlet里面做的，而它是在listener和filter之后执行。
 * 如果我们想在listener和filter里面@Autowired某个bean，肯定是不行的，因为filter初始化的时候，此时bean还没有初始化，无法自动装配。
 */
//public class UserFilter implements Filter {
//
//    @Autowired
//    private User user;
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        user.say();
//    }
//
//    @Override
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
//        throws IOException, ServletException {
//
//    }
//
//    @Override
//    public void destroy() {
//    }
//}

public class UserFilter implements Filter {

    private User user;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        this.user = ((User)(applicationContext.getBean("userImpl")));
        user.say();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    }

    @Override
    public void destroy() {

    }
}